<!--
 * @Author: your name
 * @Date: 2021-08-18 20:24:24
 * @LastEditTime: 2021-08-18 22:33:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Self\hrsaas-86\src\views\employees\component\assign-role.vue
-->
<template>
  <el-dialog
    :visible="setRoleVisible"
    title="分配角色"
    @close="closedialog"
    @open="openDialog"
  >
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox :label="item.id" v-for="item in roleslist" :key="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">
        确定
      </el-button>
      <el-button size="small" @click="closedialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { getuserImgById, reqAssignRoles } from '@/api/user'
export default {
  name: 'SelfAssignRole',

  data() {
    return {
      roleslist: [], // 所有的角色列表
      checkList: [], //  多选框组绑定的数据
      loading: false
    }
  },
  props: {
    setRoleVisible: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },

  mounted() {},
  created() {
    // this.getRoleslist()
  },
  methods: {
    //   通知父组件关闭对话框
    closedialog() {
      this.$emit('update:setRoleVisible', false)
    },
    // 获取所有角色列表
    async getRoleslist() {
      //   this.loading = true
      //   const {
      //     data: { rows }
      //   } = await reqGetRoleList(1, 10) // 正确的方案是后端提供一个获取所有角色列表的接口
      //   const {
      //     data: { roleIds }
      //   } = await getuserImgById(this.userId) // 有什么角色其实就是有什么roleIds
      //   this.checkList = roleIds
      //   this.roleslist = rows
      //   this.loading = false
      Promise.all([reqGetRoleList(1, 1000), getuserImgById(this.userId)]).then(
        res => {
          // console.log(res) // 所有的promise的结果会被收集到一个数组中
          res.forEach(item => {
            if (item.message === '获取角色列表成功') {
              this.roleslist = item.data.rows
            } else {
              this.checkList = item.data.roleIds
            }
          })
          this.loading = false
        }
      )
    },
    // 在对话框打开时发请求而不是组件创建时
    openDialog() {
      this.getRoleslist()
    },
    // 给员工分配角色
    async assignRole() {
      // 1.发送请求
      const { message } = await reqAssignRoles({
        id: this.userId,
        roleIds: this.checkList
      })
      //   2.提示用户
      this.$message.success(message)
      //   3.关闭对话框
      this.closedialog()
    }
  }
}
</script>

<style lang="scss" scoped></style>
